<?php

namespace App\Models\System;

use App\Traits\DateTrait;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Menus extends Model
{
    use DateTrait;
    private const CACHE_KEY = 'SYSTEM_MENUS';
    protected $table = 'system_menus';
    protected $fillable = ['name', 'display_name', 'url', 'icon', 'parent_id', 'genre', 'status'];

    public function children()
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }

    /**
     * @return mixed
     */
    public static function getAllMenus()
    {
        return Cache::remember(self::CACHE_KEY, Carbon::now()->addHours(2), static function () {
            return self::query()->where('status', 1)->get(['id', 'name', 'display_name', 'url', 'icon', 'genre', 'parent_id'])->toArray();
        });
    }

    protected static function booted()
    {
        static::saved(static function () {
            Cache::forget(self::CACHE_KEY);
        });

        static::deleted(static function () {
            Cache::forget(self::CACHE_KEY);
        });
    }
}
